import re

import logging

from waveapi import events
from waveapi import model
from waveapi import robot
from waveapi import document

regexp=re.compile('(http://[^/]+/[^.]+\.(gif|jpg|png))')

def onEnter(properties, context):
  logging.debug('onEnter('+str(properties)+' -- '+str(context)+')')
  wavelet = context.GetRootWavelet()
#  wavelet.CreateBlip().GetDocument().SetText("Inbedding enabled")
  
  root = context.GetBlipById(wavelet.GetRootBlipId())
  logging.debug('root blip: '+str(root))
#  convertBlips(context, root)

def onBlip(properties, context):
  logging.debug('onBlip('+str(properties)+' -- '+str(context)+')')
  blip = context.GetBlipById(properties['blipId'])
  
  convertBlip(blip)

def convertBlips(context, blip):
  if not blip:
    logging.debug('no blips')
    return
  convertBlip(blip)
  
  for childId in blip.GetChildBlipIds():
    child=context.GetBlipById(childId)
    convertBlips(context, child)

def convertBlip(blip):
  if not blip:
    logging.debug('no blip')
    return
  doc = blip.GetDocument()      
  logging.debug('doc: '+str(doc))
  text=doc.GetText()
  logging.debug('text: '+str(text))
  matches=regexp.findall(text)
  logging.debug('matches: '+str(matches))
    
  occurrences = range(0)
  start=0
  for url, ext in matches:
    start = text.find(url, start)
    occurrences.append([start, len(url), url])
    start += 1
  occurrences = sorted(occurrences)
  occurrences.reverse()
  for occurrence in occurrences:
    doc.SetTextInRange(document.Range(occurrence[0],occurrence[0]+occurrence[1]), '  ')
    doc.InsertElement(occurrence[0] + 1, document.Image(url=occurrence[2]))

if __name__ == '__main__':
  myRobot = robot.Robot('inbeddable',
      image_url='http://inbeddable.appspot.com/static/icon.png',
      version='1',
      profile_url='http://inbeddable.appspot.com/'
  )
  myRobot.RegisterHandler(events.BLIP_SUBMITTED, onBlip)
  myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, onEnter)
  myRobot.Run(debug=True)
